package views

import (
	"errors"
	"fanqiechaodan-blog/common"
	"fanqiechaodan-blog/models"
	"fanqiechaodan-blog/service"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"strings"
)

func (*HTMLApi) Detail(writer http.ResponseWriter, request *http.Request) {
	detail := common.Template.Detail
	// 获取路径参数
	path := request.URL.Path
	pidStr := strings.TrimSuffix(strings.TrimPrefix(path, "/post/"), models.HTML_SUFFIX)
	pid, err := strconv.Atoi(pidStr)
	if err != nil {
		zap.S().Errorf("解析路由参数失败;路由:%s;err:%s", path, err.Error())
		detail.WriteError(writer, errors.New("解析参数失败"))
		return
	}
	res, err := service.GetPostDetail(pid)
	if err != nil {
		detail.WriteError(writer, errors.New("查询失败"))
		return
	}
	common.UpdateViewCount(pid)
	detail.WriteData(writer, res)
}

func (*HTMLApi) Writing(writer http.ResponseWriter, request *http.Request) {
	writing := common.Template.Writing
	res, err := service.Writing()
	if err != nil {
		writing.WriteError(writer, errors.New("加载失败"))
		return
	}
	writing.WriteData(writer, res)
}
